package com.benew.ntt.player

import android.content.Context
import com.benew.ntt.player.audiofocus.AudioFocusChangeListener
import com.benew.ntt.player.audiofocus.AudioFocusListener
import com.google.android.exoplayer2.util.Log
import com.ntt.core.nlogger.NLogger

object NttPlayCtrl : IAudioBase, AudioFocusListener {
    private const val TAG = "NttPlayCtrl"
    private var mAudioPlayer: NttAudioPlayer? = null
    private var mAudioFocusChangeListener: AudioFocusChangeListener? = null


    override fun init(context: Context) {
        mAudioPlayer = NttAudioPlayer().apply {
            init(context)
            initAudioFocus(context)
        }
    }

    private fun initAudioFocus(context: Context) {
        mAudioFocusChangeListener = AudioFocusChangeListener(context)
        mAudioFocusChangeListener?.setOnAudioFocusListener(this)
    }

    override fun release() {
        mAudioFocusChangeListener?.abandonAudioFocus()
        mAudioFocusChangeListener = null
        mAudioPlayer?.release()
    }


    fun playAudio(audioItem: AudioItem) {
        mAudioFocusChangeListener?.requestAudioFocus()?.run {
            if (this) {
                val audios = listOf(audioItem)
                mAudioPlayer?.playAudios(audios)
            }
        }
    }


    fun playAudios(audioItems: List<AudioItem>) {
        mAudioFocusChangeListener?.requestAudioFocus()?.run {
            if (this) {
                audioItems.takeIf {
                    it.isNotEmpty()
                }?.run {
                    mAudioPlayer?.playAudios(this)
                }
            }
        }
    }

    fun setPlayAudioListener(audioPlayerListener: IAudioPlayListener?) {
        mAudioPlayer?.setAudioPlayListener(audioPlayerListener)
    }

    fun pause() {
        mAudioPlayer?.pause()
    }

    fun resume() {
        mAudioPlayer?.resume()
    }

    fun stop() {
        mAudioPlayer?.stop()
    }

    fun isPlaying(): Boolean {
        return mAudioPlayer?.isPlaying() ?: false
    }

    override fun audioFocusGain() {

    }

    override fun audioFocusLoss() {
        NLogger.d(TAG, "audioFocusLoss 短音频播放器，音频失去焦点，暂停播放")
        stop()
    }

    override fun audioFocusLossTransient() {
        NLogger.d(TAG, "audioFocusLossTransient 短音频播放器，音频失去焦点，停止播放")
        stop()
    }

    override fun audioFocusLossTransientCanDuck() {

    }


}